<?php
namespace App\Logic\Storage;

use App\Logic\Basics\SerialNo;
use App\Models\Basics\Account;
use App\Models\Storage\CountryInventory;
use App\Models\Storage\RecordInventory;
use App\Models\Storage\StorageOwe;
use Illuminate\Support\Facades\DB;
class BackOweInventory
{
    public static function exeBack(){
        try{
            $so = StorageOwe::select('id','psku_id','num')->get();
            $i = 0;
            $num = 100;
            while(true){
                if($so->isEmpty())break;
                $_so = $so->splice($i,$num);
                DB::beginTransaction();
                foreach($_so as $item){
                    $ci = CountryInventory::where('country_id',Account::PUBLIC_COUNTRY)
                        ->where('psku_id',$item->psku_id)
                        ->where('instant_num','>',0)
                        ->first();
                    if(!$ci)continue;
                    $num = $ci->instant_num + $item->num;
                    $recordNo = SerialNo::getRcNo();
                    if($num >= 0){
                        RecordInventory::create([
                            'record_no' => $recordNo,
                            'a_type' => RecordInventory::OWE_STOCK,
                            'r_type' => 2,
                            'country_id' => Account::PUBLIC_COUNTRY,
                            'psku_id' => $item->psku_id,
                            'num' => $item->num,
                            'user_id' => 1
                        ]);
                        $ci->instant_num = $num;
                        $ci->save();
                        $item->delete();
                    }else{
                        RecordInventory::create([
                            'record_no' => $recordNo,
                            'a_type' => RecordInventory::OWE_STOCK,
                            'r_type' => 2,
                            'country_id' => Account::PUBLIC_COUNTRY,
                            'psku_id' => $item->psku_id,
                            'num' => -$ci->instant_num,
                            'user_id' => 1
                        ]);
                        $ci->instant_num = 0;
                        $ci->save();
                        $item->num = $num;
                        $item->save();
                    }
                }
                DB::commit();
            }
        }catch (\Exception $e){
            DB::rollBack();
        }
    }
}